import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pin_code_fields/flutter_pin_code_fields.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/transfer_user_entity.dart';
import 'package:seedfour/app/theme.dart';

import '../../constants.dart';
import 'logic.dart';

class TransferPage extends StatelessWidget {
  TransferPage({Key? key}) : super(key: key);

  final logic = Get.find<TransferLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text('余额转账'),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Form(
        key: logic.formKey,
        child: ListView(
          padding: EdgeInsets.symmetric(
              vertical: kSpaceMedium, horizontal: kSpaceSmall),
          children: [
            _buildDropdownButton(),
            SizedBox(height: kSpaceSmall),
            _buildTransferAmount(),
            SizedBox(height: kSpaceSmall),
            _buildRemark(),
            SizedBox(height: kSpaceMedium),
            _buildWithdrawButton(),
            SizedBox(height: kSpaceMedium),
          ],
        ),
      ),
    );
  }

  // 生成提现按钮小部件
  Widget _buildWithdrawButton() {
    return SizedBox(
      width: double.infinity,
      height: 50,
      child: FilledButton(
        // 直角矩形样式
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(kRadiusSmall),
          ),
        ),
        onPressed: () {
          if (logic.formKey.currentState!.validate()) {
            logic.formKey.currentState!.save();
            _showPasswordDialog();
          }
        },
        child: const Text('转账'),
      ),
    );
  }

  Widget _buildRemark() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '附言',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          TextFormField(
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: '请输入',
              hintStyle: TextStyle(
                fontSize: kFontSizeSmall,
                color: AppColor.colorFontLabelGrey,
              ),
              contentPadding:
                  EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
            ),
            controller: logic.remarkController,
            style: const TextStyle(color: Colors.black87),
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  Widget _buildTransferAmount() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: kSpaceMedium),
          Text(
            '转账金额',
            style: TextStyle(
              fontSize: kFontSizeSmall,
              color: AppColor.colorFontBlack,
            ),
          ),
          TextFormField(
            controller: logic.amountController,
            decoration: InputDecoration(
              icon: SvgPicture.asset('assets/icons/ic_money.svg',
                  width: kIconSizeSmall, height: kIconSizeSmall),
              contentPadding:
                  EdgeInsets.only(top: kSpaceSmall, bottom: kSpaceMini),
              border: InputBorder.none,
            ),
            keyboardType: TextInputType.number,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入转账金额';
              }
              if (!RegExp(r'^[1-9]\d*(\.\d{1,2})?$').hasMatch(value)) {
                return '请输入正确的金额';
              }
              return null;
            },
          ),
          const Divider(),
          SizedBox(height: kSpaceSmall),
          Obx(
            () => Text(
              '可用余额 ${logic.balance.value}',
              style: TextStyle(
                fontSize: kFontSizeMini,
                color: AppColor.colorFontGrey,
              ),
            ),
          ),
          SizedBox(height: kSpaceMedium),
        ],
      ),
    );
  }

  // 下拉选项框，选中后显示TransferUserEntity中的name跟mobile
  Widget _buildDropdownButton() {
    return Container(
      padding: EdgeInsets.all(kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kRadiusMedium),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '转账对象',
            style: TextStyle(
              fontSize: kFontSizeMedium,
              color: AppColor.colorFontBlack,
              fontWeight: AppFont.fontMedium,
            ),
          ),
          Obx(
            () => DropdownButtonFormField2<TransferUserEntity>(
              isExpanded: true,
              iconStyleData: const IconStyleData(
                  icon: Icon(
                Icons.keyboard_arrow_down_rounded,
                color: AppColor.colorFontBlack,
              )),
              decoration: InputDecoration(
                hintText: '选择转账对象',
                hintStyle: TextStyle(
                  fontSize: kFontSizeSmall,
                  color: AppColor.colorFontLabelGrey,
                  fontWeight: AppFont.fontRegular,
                ),
                border: InputBorder.none,
              ),
              dropdownStyleData: const DropdownStyleData(
                padding: EdgeInsets.all(0),
                maxHeight: 400,
                elevation: 1,
                decoration: BoxDecoration(
                  border: Border.fromBorderSide(
                    BorderSide(color: Color(0xFFE3E6EB)),
                  ),
                  borderRadius: BorderRadius.all(Radius.circular(4)),
                  color: Colors.white,
                ),
              ),
              dropdownSearchData: DropdownSearchData(
                searchController: logic.searchController,
                searchInnerWidgetHeight: 50,
                searchInnerWidget: Container(
                  height: 50,
                  padding: const EdgeInsets.only(
                    top: 8,
                    bottom: 4,
                    right: 8,
                    left: 8,
                  ),
                  child: TextFormField(
                    expands: true,
                    maxLines: null,
                    controller: logic.searchController,
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 8,
                      ),
                      hintText: '输入关键词筛选用户',
                      hintStyle: TextStyle(
                        fontSize: kFontSizeMini,
                        color: AppColor.colorFontLabelGrey,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(kRadiusSmall),
                      ),
                    ),
                  ),
                ),
                searchMatchFn: (item, searchValue) {
                  return item.value.toString().contains(searchValue);
                },
              ),
              onChanged: (TransferUserEntity? newValue) {
                if (newValue != null) {
                  logic.selectedUser.value = newValue;
                }
              },
              items: logic.transferUsers
                  .map<DropdownMenuItem<TransferUserEntity>>(
                      (TransferUserEntity value) {
                return DropdownMenuItem<TransferUserEntity>(
                    value: value,
                    child: Text('${value.name!}（${value.mobile!}）'));
              }).toList(),
              validator: (value) {
                if (value == null) {
                  return '请选择转账对象';
                }
                return null;
              },
            ),
          ),
        ],
      ),
    );
  }

  void _showPasswordDialog() {
    logic.initPasswordController();

    showModalBottomSheet(
        context: Get.context!,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(15.w)),
        ),
        builder: (context) {
          return SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: kSpaceTiny),
                  Stack(
                    alignment: Alignment.center,
                    children: [
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          textAlign: TextAlign.center,
                          '请输入6位支付密码',
                          style: TextStyle(
                            fontSize: kFontSizeMedium,
                            color: AppColor.colorFontBlack,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: IconButton(
                          onPressed: () => {Get.back()},
                          icon: SvgPicture.asset(
                              'assets/icons/ic_cancel_black.svg',
                              width: kIconSizeMini),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: kSpaceTiny),
                  const Divider(),
                  SizedBox(height: kSpaceBig),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: kSpaceLarge),
                    child: PinCodeFields(
                      length: 6,
                      autofocus: true,
                      fieldWidth: 40.w,
                      fieldHeight: 40.w,
                      padding: EdgeInsets.only(top: 4.w),
                      fieldBackgroundColor: AppColor.colorRectangleGrey,
                      fieldBorderStyle: FieldBorderStyle.square,
                      borderColor: AppColor.colorRectangleGrey,
                      activeBorderColor: AppColor.colorRectangleGrey,
                      activeBackgroundColor: AppColor.colorRectangleGrey,
                      borderRadius: BorderRadius.circular(5.w),
                      keyboardType: TextInputType.number,
                      obscureText: true,
                      textStyle: TextStyle(
                        fontSize: kFontSizeBig,
                        color: AppColor.colorFontBlack,
                      ),
                      controller: logic.payPasswordController,
                      onComplete: (text) => {
                        Get.back(),
                        logic.submitTransfer(),
                      },
                    ),
                  ),
                  SizedBox(height: kSpaceBig),
                ],
              ),
            ),
          );
        });
  }
}
